package com.dylan.shot.head.shiro;

import com.dylan.shot.common.model.Member;
import com.dylan.shot.head.service.MemberAuthenticateService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Dylan on 2017/9/12.
 */
public class EmailRealm extends AuthorizingRealm {
    private Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemberAuthenticateService memberAuthenticateService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole("admin");
        authorizationInfo.addStringPermission("all");
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = (String) authenticationToken.getPrincipal();
        Member member = memberAuthenticateService.getMemberByEmail(email);
        if (member == null) {
            LOG.info("通过email[{}]未查询到用户", email);
            throw new UnknownAccountException("未知用户");
        }
        return new MySimpleAuthenticationInfo(member, member.getEmail(), member.getPassword(), getName());
    }

    // 清除缓存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}
